/**
 * @description 工具栏：查询组件
 * @author chenyan
 */

import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Switch, Select, InputNumber, TreeSelect, Row, Col } from 'antd';
import { fixedNum } from '../../../utils/utils';
import style from './index.less';
import { TableC, DATA_ENTRY, AdvancedSearch, codeType } from '../../../comps';

const { SHOW_CHILD } = TreeSelect;
const { Option } = Select;
const ctx = { top: 0 };
@Form.create()
class TabItemC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      height: 0,
      tableData: [],
      columns: [],
      currentPage: 1,
      pageSize: 10,
      range: 0, // 分析范围
      bondType: '', // 债券类型
      creditRate: '', // 债券评级
      switchValue: true,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const data = {
      range: 0,
      userId: localStorage.getItem('antd-pro-userId'),
      type: this.props.activeKey,
      flag: 1,
    };

    if (sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '13') {
        const {
          form: { setFieldsValue },
        } = this.props;
        this.securityCodeRef?.setSelect(obj.code);
        setFieldsValue({
          yieldBias: 50,
          valuationBias: 1,
        });
        data.yieldBias = 50;
        data.valuationBias = 1;
        sessionStorage.removeItem('jumpInfo');
        this.setState(
          {
            secucode: obj.securityCode,
          },
          () => {
            this.onSearch(data);
          },
        );
      }
    } else {
      data.yieldBias = 10;
      data.valuationBias = 3;
      this.onSearch(data);
    }
    this.resize();
    window.addEventListener('resize', this.resize);
  }

  UNSAFE_componentWillReceiveProps() {
    // 适配用户视图跳转至,定位指定的产品、日期
    if (sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      const data = {
        range: 0,
        yieldBias: 50,
        valuationBias: 1,
        userId: localStorage.getItem('antd-pro-userId'),
        type: this.props.activeKey,
        flag: 1,
      };
      if (obj.type == '13') {
        const {
          form: { setFieldsValue },
        } = this.props;
        this.securityCodeRef?.setSelect(obj.code);
        setFieldsValue({
          yieldBias: 50,
          valuationBias: 1,
        });
        sessionStorage.removeItem('jumpInfo');
        this.onSearch(data);
      }
    }
  }

  // 更该债券评级值的格式
  changeRate = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        this.props.onRef(this);
        data.push({
          title: item.value,
          value: item.code,
        });
      });
    }
    return data;
  };

  // 更该分析范围值的格式
  changeRange = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({
          title: item.value,
          value: item.code,
        });
      });
    }
    return data;
  };

  changeTreeData = (arr) => {
    const tempArr = [];
    arr.forEach((item) => {
      tempArr.push({
        value: item.code,
        title: item.value,
        selectable: !item.children?.length,
        children: this.changeTreeData(item.children || []),
      });
    });
    return tempArr;
  };

  selectChange = (value) => {
    const { range, bondType, creditRate } = this.state;
    const {
      form: { getFieldsValue },
      activeKey,
    } = this.props;
    const values = getFieldsValue();
    const data = {
      range,
      yieldBias: value,
      valuationBias: values.valuationBias,
      userId: localStorage.getItem('antd-pro-userId'),
      type: activeKey,
      bondType,
      creditRate,
    };
    this.onSearch(data);
  };

  inputChange = (value) => {
    const { range, bondType, creditRate } = this.state;
    const {
      form: { getFieldsValue },
      activeKey,
    } = this.props;
    const values = getFieldsValue();
    if (value == null || value == '') {
      message.warning('值不可以为空!');
      return;
    }
    const data = {
      range,
      yieldBias: values.yieldBias,
      valuationBias: value,
      userId: localStorage.getItem('antd-pro-userId'),
      type: activeKey,
      bondType,
      creditRate: creditRate || '',
    };
    this.onSearch(data);
  };

  // 点击查询按钮
  onSearch = (values) => {
    this.queryData(values, 'first');
    if (this.state.switchValue) {
      clearInterval(this.state.timeoutId);
      const timeoutId = setInterval(() => {
        this.queryData(values, 'sec');
      }, 7000);
      this.setState({
        timeoutId,
      });
    }
  };

  // 定时刷新按钮
  switchChange = (e) => {
    if (e) {
      const { range, bondType, creditRate, secucode } = this.state;
      const {
        form: { getFieldsValue },
        activeKey,
      } = this.props;
      const values = getFieldsValue();
      const data = {
        range,
        yieldBias: values.yieldBias,
        valuationBias: values.valuationBias || '',
        userId: localStorage.getItem('antd-pro-userId'),
        type: activeKey,
        bondType: bondType ? bondType : '',
        creditRate: creditRate ? creditRate : '',
        secucode,
      };
      this.setState(
        {
          switchValue: true,
        },
        () => {
          this.onSearch(data);
        },
      );
    } else {
      clearInterval(this.state.timeoutId);
      this.setState({
        switchValue: false,
      });
    }
  };

  componentWillUnmount() {
    clearInterval(this.state.timeoutId);
  }

  // 查询数据
  queryData = (values, step) => {
    const { secucode } = this.state;
    // VTScroll(idSet,{top:0});   //重新查询滚动到顶部
    values.source = values.type == '中债' ? 0 : values.type == '上清' ? 1 : 2;
    const obj = {};
    if (secucode) {
      obj.secucode = secucode;
    }
    for (const key in values) {
      if (Object.hasOwnProperty.call(values, key)) {
        const element = values[key];
        if (element !== '' && element !== null && element != undefined) obj[key] = element;
      }
    }
    this.props.dispatch({
      type: 'bondAnalysisM/queryCreditBondMonitor',
      payload: {
        ...obj,
        currentPage: 1,
        numInPage: 3000,
      },
      callback: (res) => {
        const params = {
          ...values,
          currentPage: 1,
          numInPage: 3000,
        };
        if (res) {
          this.setState({
            nowActiveKey: this.props.activeKey,
            searchParams: params,
            tableData: res.tableData,
            columns: res.columns,
          });
        }
      },
    });
  };

  // 工具栏渲染
  renderToolbar() {
    const {
      globalM: {
        dataDictionary: { CREDITBND_MONITOR_BONDTYPEI = [] },
      },
    } = this.props;
    const {
      form: { getFieldDecorator, getFieldsValue, resetFields, setFieldsValue },
      activeKey,
      CREDITBND_MONITOR_BIASBP = [],
      CREDITBND_MONITOR_RANGE = [],
      CREDITBND_MONITOR_RATINGCODE = [],
    } = this.props;
    const creditRate = this.changeRate(CREDITBND_MONITOR_RATINGCODE);
    const range = this.changeRange(CREDITBND_MONITOR_RANGE);
    const bondTypeList = this.changeTreeData(CREDITBND_MONITOR_BONDTYPEI);

    const searchProps = {
      dataSource: [
        {
          dataIndex: 'tradingCode',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          codeType: codeType.zq,
          onChange: (e) => {
            this.setState({
              secucode: e?.secucode,
            });
          },
          onRef: (ref) => (this.securityCodeRef = ref),
        },
        {
          dataIndex: 'bondType',
          title: '债券类型',
          type: DATA_ENTRY.TREESELECT,
          isMultiple: true,
          dataSource: bondTypeList,
          treeCheckable: true,
          treeDefaultExpandAll: true,
          showCheckedStrategy: SHOW_CHILD,
          allowClear: true,
        },
        {
          dataIndex: 'creditRate',
          title: '债券评级',
          type: DATA_ENTRY.SELECT,
          dataSource: creditRate,
          allowClear: true,
        },
        {
          dataIndex: 'range',
          title: '分析范围',
          type: DATA_ENTRY.SELECT,
          dataSource: range,
          initialValue: range.length ? range[0].value : '',
        },
      ],
      onQuery: (e) => {
        const values = getFieldsValue();
        console.log(e);
        if (e.range === undefined || values.valuationBias === undefined || values.valuationBias === null || values.valuationBias === '' || values.yieldBias === undefined) {
          message.warning('请填写完整查询条件!');
          return;
        }
        e.bondType = e.bondType ? e.bondType.join(',') : '';
        this.setState(
          {
            isReset: false,
            range: e.range,
            bondType: e.bondType,
            creditRate: e.creditRate,
          },
          () => this.onSearch({ ...e, ...values, userId: localStorage.getItem('antd-pro-userId'), type: activeKey }),
        );
      },
      onClear: () => {
        resetFields();
        this.setState(
          {
            isReset: true,
          },
          () => {
            // 成交选择模块重置
            setFieldsValue({
              yieldBias: 10,
              initialValue: 3,
            });
            const data = {
              range: 0,
              yieldBias: 10,
              valuationBias: 3,
              userId: localStorage.getItem('antd-pro-userId'),
              type: this.props.activeKey,
              flag: 1,
              secucode: undefined,
            };
            this.onSearch(data);
          },
        );
      },
    };

    return (
      <div>
        <AdvancedSearch {...searchProps} />
        <div style={{ margin: '10px', position: 'relative' }}>
          <div style={{ display: 'flex' }}>
            <div className={style.flexForm}>
              <span>
                收益率偏离度=| 最新成交收益率 - {activeKey}
                {'估值收益率 | >'}
              </span>
              <Form.Item>
                {getFieldDecorator('yieldBias', {
                  initialValue: 10,
                })(
                  <Select style={{ width: 80 }} onChange={(value) => this.selectChange(value)}>
                    {CREDITBND_MONITOR_BIASBP.length
                      ? CREDITBND_MONITOR_BIASBP.map((item, i) => (
                          <Option value={item.code} key={i}>
                            {item.value}
                          </Option>
                        ))
                      : null}
                  </Select>,
                )}
              </Form.Item>
              <span>bp</span>
            </div>
            <div className={style.flexForm} style={{ marginLeft: '20px' }}>
              <span>
                净价偏离度=| 最新成交净价 - {activeKey}估值净价 | / {activeKey}
                {'估值净价 >'}
              </span>
              <Form.Item>
                {getFieldDecorator('valuationBias', {
                  initialValue: 3,
                })(<InputNumber width={80} min={0.01} precision={2} parser={(inValue) => inValue.replace(/\$\s?|(,*)/g, '')} onChange={(value) => this.inputChange(value)} />)}
              </Form.Item>
              <span>%</span>
            </div>
          </div>
          <div style={{ position: 'absolute', top: '10px', right: '0px', zIndex: '2' }}>
            <Switch defaultChecked={true} checked={this.state.switchValue} onChange={this.switchChange} style={{ marginRight: '10px' }} />
            定时刷新
          </div>
        </div>
      </div>
    );
  }

  // 债券详情页跳转
  goToDetail = (row) => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const obj = {
      bondID: row.BONDID,
      type: this.props.activeKey,
      price: getFieldsValue().yieldBias,
      degree: getFieldsValue().valuationBias,
      exchangeCode: row.exchangeCode,
      tradingCode: row.tradingCode,
    };
    sessionStorage.setItem('bondInfo', JSON.stringify(obj));
    this.props.dispatch(routerRedux.push(`/marketAnalysis/bondDeviationDetail`));
  };

  // 动态渲染高度
  resize = () => {
    const height = document.body.offsetHeight - 415;
    this.setState({
      height,
    });
  };

  renderTable = () => {
    const { tableData, columns = [], height } = this.state;
    const { idSet, activeKey } = this.props;
    const { loading } = this.props;
    console.log('tableData', tableData);
    columns.map((item, key) => {
      item.dataIndex = item.key;
      if (key > 0) {
        item.width = '11.13%';
      }
      if (item.key == 'BIASCNT' || item.key == 'TRANSACTIONCNT') {
        item.width = '5.6%';
      }
      if (item.key == 'TRADENETPRICE' || item.key == 'NETVALUATION') {
        item.render = (text) => {
          return text ? fixedNum(text) : text == null ? '--' : 0;
        };
      }
      if (item.key != 'SYMBOL') {
        item.align = 'right';
      }
      // if (item.key == 'NETVALUATIONBIAS') {
      //     //净价偏离度
      //     item.render = (text, record) => {
      //         if (text === null || text === undefined) {
      //             return '--';
      //         } else {
      //             return (Number(text) * 100).toFixed(2);
      //         }
      //     }
      // }
      if (item.key == 'SYMBOL') {
        item.render = (text, record) => {
          return (
            <a
              onClick={() => {
                this.goToDetail(record);
              }}
            >
              {text}
            </a>
          );
        };
      }
      if (item.key == 'EVALUTEDYIELD') {
        item.title = `${activeKey}估值收益率`;
      }
      if (item.key == 'NETVALUATION') {
        item.title = `${activeKey}估值净价`;
      }
    });
    tableData.map((item, index) => {
      item.id = index;
    });
    return (
      <div>
        <TableC columns={columns} dataSource={tableData} scroll={{ y: 500 }} selfScrollY={true} page={false} rowKey='key' hidePage={true} bigTable={true} />
      </div>
    );
  };

  render() {
    return (
      <div>
        {this.renderToolbar()}
        {this.renderTable()}
      </div>
    );
  }
}

export default connect(({ bondAnalysisM, loading, globalM }) => ({
  bondAnalysisM,
  loading: loading.effects['bondAnalysisM/queryCreditBondMonitor'],
  globalM,
}))(TabItemC);
